<template>
  <div>
    <van-nav-bar title="登录页" left-text="返回" left-arrow @click-left="goBack" />

    <van-form @submit="onSubmit">
      <van-field
        v-model="loginForm.username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        required
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="loginForm.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        required
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import * as api from "@/request/api/login.js"

import { createNamespacedHelpers } from 'vuex'
const { mapMutations } = createNamespacedHelpers('userModule')

export default {
  data(){
    return{
      loginForm:{}//登录表单对象
    }
  },
  methods: {
    ...mapMutations(["GET_TOKEN"]),
    async API_login(name,pwd){
      let result = {
        name,
        pwd
      }
      return await api.login(result)
    },
    goBack() {
      this.$router.go(-1);
    },
    async onSubmit(){
      let {username,password} = this.loginForm
      let res = await this.API_login(username,password)
      // localStorage.setItem("shopToken",res.data.token)//存储token

      // this.$store.commit("userModule/GET_TOKEN",res.data.token)//不使用辅助函数的写法
      

      if(res.data.code === 1000){
        // this.GET_TOKEN(res.data.token)//使用辅助函数的写法
        localStorage.setItem("token",res.data.token)
        this.$eventBus.$emit("getToken",res.data.token)

        this.$toast.success("登录成功")
        this.$router.push("/user")
      }else{
        this.$toast.fail("登录失败，请检查账号和密码。")
      }
    }
  },
  created() {}
};
</script>

<style>
</style>

